package com.sszka.demo.web;

import com.sszka.demo.util.WordUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.util.StringUtil;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.tomcat.util.http.fileupload.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/demo")
@Slf4j
public class DemoController {
    @Autowired
    private TemplateEngine templateEngine;


    @RequestMapping("index")
    public String index(){
        return "upload";
    }



    @ResponseBody
    @RequestMapping("/upload")
    public Object upload(@RequestParam(value = "file",required = false) MultipartFile file) {
        try {
            InputStream inputStream = file.getInputStream();
            //进行版本选择解析方式
            Workbook wb = null;
            String fileName = file.getOriginalFilename();
            if (fileName.endsWith(".xlsx")) {
                wb = new XSSFWorkbook(inputStream);

            } else if (fileName.endsWith(".xls")) {
                wb = new HSSFWorkbook(inputStream);
            }
            Sheet sheet = wb.getSheetAt(0);
            int rowNum = sheet.getLastRowNum() + 1;
            List< List<Object>> list = new ArrayList<>();
            //行循环开始
            for (int i = 0; i < rowNum; i++) {
                List<Object> map = new ArrayList<>();
                //行
                Row row = sheet.getRow(i);
                //每行的最后一个单元格位置
                int cellNum = row.getLastCellNum();
                String cellValue = null;
                //列循环开始
                for (int j = 0; j < cellNum; j++) {

                    Cell cell = row.getCell(Short.parseShort(j + ""));
                    if (null != cell) {
                        // 判断excel单元格内容的格式，并对其进行转换，以便插入数据库
                        switch (cell.getCellType()) {
                            case HSSFCell.CELL_TYPE_NUMERIC:
                                cellValue = cell.getNumericCellValue() + " ";
                                break;
                            case HSSFCell.CELL_TYPE_STRING:
                                cellValue = StringUtils.trim(cell.getStringCellValue()) + " ";
                                break;
                            case HSSFCell.CELL_TYPE_FORMULA:
                                break;
                            default:
                                cellValue = " ";
                                break;
                        }
                    } else {
                        cellValue = " ";
                    }
                    map.add(cellValue);
                }
                list.add(map);
            }
            return list;
        } catch (Exception e) {
            e.printStackTrace();
            return "上传失败";
        }

    }

    //@ResponseBody
    @RequestMapping("/downloadWord")
    public void downloadWord(@RequestParam(value = "file",required = false) MultipartFile file,HttpServletResponse response) {
        try {
            InputStream inputStream = file.getInputStream();
            //进行版本选择解析方式
            Workbook wb = null;
            String word = "";
            String fileName = file.getOriginalFilename();

            if (fileName.endsWith(".xlsx")) {
                wb = new XSSFWorkbook(inputStream);

            } else if (fileName.endsWith(".xls")) {
                wb = new HSSFWorkbook(inputStream);
            }
            Sheet sheet = wb.getSheetAt(0);
            int rowNum = sheet.getLastRowNum() + 1;
            List< List<Object>> list = new ArrayList<>();
            //行循环开始
            for (int i = 0; i < rowNum; i++) {
                List<Object> map = new ArrayList<>();
                //行
                Row row = sheet.getRow(i);
                //每行的最后一个单元格位置
                int cellNum = row.getLastCellNum();
                String cellValue = null;
                //列循环开始
                for (int j = 0; j < cellNum; j++) {

                    Cell cell = row.getCell(Short.parseShort(j + ""));
                    if (null != cell) {
                        // 判断excel单元格内容的格式，并对其进行转换
                        switch (cell.getCellType()) {
                            case HSSFCell.CELL_TYPE_NUMERIC:
                                cellValue = cell.getNumericCellValue() + " ";
                                break;
                            case HSSFCell.CELL_TYPE_STRING:
                                cellValue = StringUtils.trim(cell.getStringCellValue()) + " ";
                                break;
                            case HSSFCell.CELL_TYPE_FORMULA:
                                break;
                            default:
                                cellValue = " ";
                                break;
                        }
                    } else {
                        cellValue = " ";
                    }
                    word = cellValue+","+word;
                    map.add(cellValue);
                }
                list.add(map);
            }
            log.debug(list.toString());

            Map<String,Object> variables = new HashMap<>();
            variables.put("title",word);

            WordUtil.download(templateEngine,"word",variables,response,fileName.substring(0,fileName.lastIndexOf("."))+".docx");
        } catch (Exception e) {
            e.printStackTrace();

        }

    }



}
